package com.rzgeo.wcgallay;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.rzgeo.rzmaplib.util.RmlUtil;
import com.rzgeo.wcgallay.bean.WcmOssTokenBean;
import com.rzgeo.wcgallay.bean.WcmServChangePassBean;
import com.rzgeo.wcgallay.model.WcmMapModel;
import com.rzgeo.wcgallay.model.WcmSysFolder;
import com.rzgeo.wcgallay.util.WcmEnv;
import com.rzgeo.wcgallay.util.WcmUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
public class WcmLoginActv extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView _userNameView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    private final String[] reqPermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Button mEmailSignInButton;
    private Spinner _spPrjs;
    private String[] _prjTitles;
    /**
     * type : changePass
     * data : {"password":"","newpassword":"","cnewpassword":""}
     */

    private String type;
    private int CRequstCode4Down = 1222;
    private OnClickListener _onDownClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(WcmLoginActv.this, WcmReseMgrActv.class);
            startActivityForResult(intent, CRequstCode4Down);
        }
    };
    private View _hlLogin;
    private View _hlOption;
    private Button _btnSignOut;
    private Button _btnEnter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArcGISRuntimeEnvironment.setLicense("KRR9NLBtXimsbjdB");// KRR9NLBtXimsbjdB

        setContentView(R.layout.actv_login);

        _hlLogin=findViewById(R.id.ll_hl_login);
        _hlOption=findViewById(R.id.ll_hl_option);


        _btnSignOut =findViewById(R.id.btn_sign_out);
        _btnSignOut.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                _hlOption.setVisibility(View.GONE);
                _hlLogin.setVisibility(View.VISIBLE);
            }
        });

        _btnEnter=findViewById(R.id.btn_enter);
        _btnEnter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("USERNAME", _userNameView.getText().toString());
                intent.putExtra("PRJNAME", _prjTitles[_spPrjs.getSelectedItemPosition()]);

                if (((RadioButton) findViewById(R.id.rb_3dmode)).isChecked()) {
                    intent.putExtra(WcmMapModel.KMapMode, WcmMapModel.V3DScene);
                } else {
                    intent.putExtra(WcmMapModel.KMapMode, WcmMapModel.V2DMap);
                }

                intent.setClass(WcmLoginActv.this, WcmSceneActv.class);
                startActivity(intent);
            }
        });

        // Set up the login form.
        _userNameView = findViewById(R.id.tin_username);
        _userNameView.setText("test1");

        populateAutoComplete();

        mPasswordView = findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        mPasswordView.setText("111111");
        mPasswordView.requestFocus();

        mEmailSignInButton = findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setEnabled(false);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        findViewById(R.id.btn_download).setOnClickListener(_onDownClick);
//        findViewById(R.id.txv_download).setOnClickListener(_onDownClick);

        findViewById(R.id.txv_change_pass).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RmlUtil.Dialog.InputPassWord(WcmLoginActv.this,
                        "222222",
                        6,
                        new RmlUtil.Dialog.OnInputText() {
                            @Override
                            public void onResult(String content) {

                                new ChangedPassword(
                                        _userNameView.getText().toString(),
                                        mPasswordView.getText().toString(),
                                        content
                                ).execute();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });

        if (ContextCompat.checkSelfPermission(WcmLoginActv.this, reqPermission[0]) == PackageManager.PERMISSION_GRANTED) {
            enter();
        } else {
            // request permission
            int requestCode = 2;
            ActivityCompat.requestPermissions(WcmLoginActv.this, reqPermission, requestCode);
        }

        WcmEnv.getDefaultInst().init(this, new WcmEnv.OnInitialized() {
            @Override
            public void Pass() {
                try {
                    WcmSysFolder appFolder = WcmEnv.getDefaultInst().getAppStandFolder();
                    WcmSysFolder.WcmReseFolder[] reses = appFolder.listRese();
                    _prjTitles = new String[reses.length];

                    for (int i = 0; i < reses.length; i++) {
                        _prjTitles[i] = reses[i].getName();
                    }
                    _spPrjs = findViewById(R.id.sp_prjs);
                    _spPrjs.setAdapter(new ArrayAdapter<>(WcmLoginActv.this, android.R.layout.simple_spinner_dropdown_item, _prjTitles));
                    _spPrjs.setSelection(0);

                    enter();
                } catch (Exception e) {
                    new AlertDialog.Builder(WcmLoginActv.this)
                            .setTitle("注意")
                            .setMessage("如果您是第一次打开程序，请尝试重启")
                            .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    System.exit(0);
                                }
                            }).show();
                }
            }

            @Override
            public void Fail() {

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        WcmEnv.getDefaultInst().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void enter() {
        mEmailSignInButton.setEnabled(true);

    }


    /**
     * Handle the permissions request response
     */
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            enter();
//        } else {
//            // report to user that permission was denied
//            Toast.makeText(this, "授权被拒绝，无法继续",
//                    Toast.LENGTH_SHORT).show();
//        }
//    }
    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(_userNameView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        if (_prjTitles == null || _prjTitles.length < 0 || _spPrjs.getSelectedItemPosition() < 0) {
            new AlertDialog.Builder(this)
                    .setTitle("错误")
                    .setMessage("请选择一个水库进行浏览")
                    .setPositiveButton("我知道了", null)
                    .show();
            return;
        }

        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        _userNameView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = _userNameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            _userNameView.setError(getString(R.string.error_field_required));
            focusView = _userNameView;
            cancel = true;
        }
//        else if (!isEmailValid(email)) {
//            _userNameView.setError(getString(R.string.error_invalid_email));
//            focusView = _userNameView;
//            cancel = true;
//        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(WcmLoginActv.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        _userNameView.setAdapter(adapter);
    }


    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    public static class UserLogin {

        public String name;
        public String password;

        public UserLogin(String name, String password) {
            this.name = name;
            this.password = password;
        }
    }

    public static class LoginResult {
        public String msg;
        public ResultData data;

        public static class ResultData {
            public String name;
        }
    }

    public interface IUserLoginTask {
        public void onFinish();
    }


    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, String> {

        protected final String _userName;
        protected final String _passWord;

        UserLoginTask(String email, String password) {
            _userName = email;
            _passWord = password;
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
//            return CheckUserName(_userName, _passWord);
            return "";
        }

        @Override
        protected void onPostExecute(final String sessionId) {
            mAuthTask = null;
            showProgress(false);

            if (sessionId != null) {
                _hlLogin.setVisibility(View.GONE);
                _hlOption.setVisibility(View.VISIBLE);
//                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }

        //        作者：AlicFeng
//        链接：https://www.jianshu.com/p/ba6998e0dfa7
//        來源：简书
//        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

        /***
         *
         * @param userName
         * @param passWord
         * @return 如果成功返回SessionID，负责返回null
         */
        protected String CheckUserName(String userName, String passWord) {
            String sessionId = null;
            String path = getString(R.string.url_login);
            OutputStream outputStream = null;
            InputStream inStream = null;
            HttpURLConnection con= null;
            try {
                URL url = new URL(path);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5000);
                con.setRequestMethod("POST");

                UserLogin userLogin = new UserLogin(userName, passWord);
                //数据准备
                String data = JSON.toJSONString(userLogin);
                //至少要设置的两个请求头
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Content-Length", data.length() + "");

                //post的方式提交实际上是留的方式提交给服务器
                con.setDoOutput(true);
                outputStream = con.getOutputStream();
                outputStream.write(data.getBytes());

                //获得结果码
                int responseCode = con.getResponseCode();
                if (responseCode == 200) {
                    //请求成功
                    inStream = con.getInputStream();

                    String resultStr = inputStream2String(inStream);
//                    LoginResult result = null;
                    try {
//                        result = JSON.parseObject(resultStr, LoginResult.class);
                        if (resultStr == null)
                            WcmUtil.Tip.Toast("登录无效，网络是否通畅？");

                        if (resultStr.contains("登录成功")) {

                            String cookieValue = con.getHeaderField("Set-Cookie");
                            sessionId = cookieValue.substring(0, cookieValue.indexOf(";"));

                            WcmUtil.Tip.Toast("登录成功");
                        } else {
                            WcmUtil.Tip.Toast("登录失败，无效的用户名或者密码");
                        }

                    } catch (Exception e) {
                        WcmUtil.Tip.Toast("登录异常");
                    }
                } else {
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null)
                        outputStream.close();
                    if (inStream != null)
                        inStream.close();
                    if (con != null)
                        con.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sessionId;
        }

        public String inputStream2String(InputStream in) throws IOException {
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }
            return out.toString();
        }
    }

    public class ChangedPassword extends UserLoginTask {

        private final String _newPass;

        ChangedPassword(String email, String password, String newPass) {
            super(email, password);
            _newPass = newPass;
        }

        @Override
        protected String doInBackground(Void... params) {
            String seesionId = CheckUserName(_userName, _passWord);
            if (seesionId != null) {
                changedPassword(seesionId);
                return seesionId;
            }
            return null;
        }

        protected String changedPassword(String sessionId) {
            String path = getString(R.string.url_chang_pass);

            OutputStream outputStream = null;
            InputStream inStream = null;
            HttpURLConnection con = null;
            try {
                WcmServChangePassBean.DataBean databean;
                databean=new WcmServChangePassBean.DataBean();
                databean.setPassword(_passWord);
                databean.setNewpassword(_newPass);
                databean.setCnewpassword(_newPass);

                WcmServChangePassBean changePass = new WcmServChangePassBean();
                changePass.setData(databean);
                //数据准备
                String data = JSON.toJSONString(changePass);

                URL url = new URL(path);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5000);
//                con.setDoOutput(true);
                con.setRequestMethod("POST");
                //至少要设置的两个请求头
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Content-Length", data.length() + "");
                con.setRequestProperty("Cookie", sessionId);

                //post的方式提交实际上是留的方式提交给服务器
                outputStream = con.getOutputStream();
                outputStream.write(data.getBytes());
                con.connect();
                //获得结果码
                int responseCode = con.getResponseCode();
//
                if (responseCode == 200) {
                    //请求成功
                    inStream = con.getInputStream();
                    String json = inputStream2String(inStream);
                    LoginResult result = JSON.parseObject(json, LoginResult.class);
                    if (result.msg != null &&
                            result.msg.contains("成功")) {

                    }
                } else {
                    //请求失败
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (outputStream != null)
                        outputStream.close();
                    if (inStream != null)
                        inStream.close();
                    if (inStream != null)
                        con.disconnect();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

    }



    public class OssToken extends UserLoginTask {

        private final String _newPass;

        OssToken(String email, String password, String newPass) {
            super(email, password);
            _newPass = newPass;
        }

        @Override
        protected String doInBackground(Void... params) {
            String seesionId = CheckUserName(_userName, _passWord);
            if (seesionId != null) {
                changedPassword(seesionId);
                return seesionId;
            }
            return null;
        }

        protected String changedPassword(String sessionId) {
            String path = getString(R.string.url_osskey);

            OutputStream outputStream = null;
            InputStream inStream = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(path);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5000);
//                con.setDoOutput(true);
                con.setRequestMethod("POST");
                //至少要设置的两个请求头
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Cookie", sessionId);

                //post的方式提交实际上是留的方式提交给服务器
                //获得结果码
                int responseCode = con.getResponseCode();
//
                if (responseCode == 200) {
                    //请求成功
                    inStream = con.getInputStream();
                    String json = inputStream2String(inStream);
                    WcmOssTokenBean result = JSON.parseObject(json, WcmOssTokenBean.class);
                    if (result.getToken()!=null&&
                            RmlUtil.isValid(result.getToken().getAccessKeyId())){

                    }
                } else {
                    //请求失败
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (outputStream != null)
                        outputStream.close();
                    if (inStream != null)
                        inStream.close();
                    if (inStream != null)
                        con.disconnect();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

    }
}

